<template>
  <el-card>
    <div slot="header">
      <h3>{{ getPageTitle() }}</h3>
    </div>
    <div class="reference--body">
      <el-row type="flex" class="margin--to--bottom">
        <span v-show="isViewPage()" class="supplier--info--wrap"
          >供应商：{{ supplyInfo.supplierName }}</span
        >
        <Supply v-show="!isViewPage()" @getName="getSupplierInfoByChoosed" />
        <span class="supplier--info--wrap"
          >供应商主营品类：{{
            supplyInfo.supMainCategoryName || supplyInfo.supMainCategoryId
          }}</span
        >
        <span class="supplier--info--wrap"
          >供应商管理区域：{{ supplyInfo.supManagerHrAreaName }}</span
        >
        <span class="supplier--info--wrap"
          >运费承担方：{{ supplyInfo.freightPayer }}</span
        >
      </el-row>
      <el-row type="flex" align="middle" class="margin--to--bottom">
        <div>供货价格方式：</div>
        <span v-show="isViewPage()">{{ getSupplyPriceTypeStr() }}</span>
        <el-radio-group
          v-show="!isViewPage()"
          v-model="supplyPriceType"
          @change="handleChangeTypeBySupplyPrice"
        >
          <el-radio label="1">统一进价</el-radio>
          <el-radio label="2">区域进价</el-radio>
        </el-radio-group>
      </el-row>
      <!-- 查看页面 参考城市关系 -->
      <el-row v-show="isViewPage()" class="margin--to--bottom">
        <BasicTable
          :columns="viewReferenceCityTable.columns"
          :data-source="viewReferenceCityTable.list"
          :showPagination="false"
          :showSelectCol="false"
        />
      </el-row>
      <el-row v-show="!isViewPage()" type="flex" justify="space-between" class="margin--to--bottom">
        <el-row type="flex" align="middle">
          <div>设置参照城市关系：</div>
          <el-button type="primary" @click="handleSetRelationByReferCity"
            >设置</el-button
          >
        </el-row>
        <!-- 按钮操作栏 -->
        <BtnRender v-if="!isViewPage()" :render="renderBtnsBar" />
      </el-row>
      <el-row class="margin--to--bottom">
        <h4>供货价格相关信息如下:</h4>
        <SkusTable
          defaultMinWidth="120"
          :loading="tableInfo.loading"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
          :showActionCol="!isViewPage() || (isViewPage() && isCommitRecord())"
          :actionRender="renderTableBtnAction"
          :actionColWidth="160"
          @handleRowChange="handleRowChange"
        />
      </el-row>
      <FooterFields :footerFields="footerFields" />
    </div>
    <!-- 查看原参照信息弹框 -->
    <OriginalReferenceDialog
      :visible.sync="originalReference.visible"
      :columns="originalReference.columns"
      :originalParams="originalReference.params"
    />
    <!-- 设置参照城市弹框 -->
    <SetReferenceCity
      :visible.sync="setReferenceCity.visible"
      :supplierCode="supplyInfo.supplierCode"
      :showReferenceCityColumns="setReferenceCity.columns"
      :templateTableData="setReferenceCity.list"
      :getReferenceCityListAction="getReferenceCityList"
      @getSetCityData="getReferenceCitiesBySet"
    />
    <!-- 关联商品-SKU维度弹框 -->
    <AssociatedGoodsModal
      ref="goodsLinked"
      :columns="goodsLinked.columns"
      :requestApi="goodsLinked.requestApi"
      :requestParams="goodsLinked.requestParams"
      :distinctParams="goodsLinked.distinctParams"
      :supplyCode="supplyInfo.supplierCode"
      @submitAction="getTableDataByGoodsLinked"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySeniorLinked"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapState, mapGetters, mapMutations } from 'vuex';
/* components */
import Supply from '@/components/commodity/getSupply.vue';
import BasicTable from '@/components/BasicTable';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import OriginalReferenceDialog from '@/components/common/dialog/setReferenceCity/originalReferenceDialog';
import SetReferenceCity from '@/components/common/dialog/setReferenceCity';
import AssociatedGoodsModal from '@/components/common/dialog/associatedGoods/associatedGoodsDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar } from '@/utils/getBtnsRender';
import {
  unifiedPurchaseColumns,
  areaPurchaseColumns,
  associatedGoodsColumns,
  showReferenceCityColumns,
  originalReferCityColumns,
  viewUnifiedPurchaseColumns,
  viewAreaPurchaseColumns,
  viewReferenceCityColumns
} from '@/pages/commodity/modules/constants/referenceCityModule/modifyReferCitySingle';
import { requiredParamsOther } from '@/components/common/dialog/associatedGoods/constants/skuDimension';
import { EDIT_REFERENCE_CITY_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import { handlePriceChangeForSingleModify } from '@/utils/price';
import { isResponseSuccess, isResponseSuccessState, createExcelByExport, generateUuid } from '@/utils/bizUtils';
import { getListByMapDimensionKey, getEchoTextByValue, getCanOpeState } from '@/utils/getUtils';
import { exportTemplateService } from '@/api/finance/purchasePriceManage/editReferCity';
import { ERRORS_COLUMN } from '@/pages/commodity/modules/constants/purchaseModule/enterPrice';
import { getSupplyCityByAreaCodesService } from '@/api/commodity/common';
export default {
  components: {
    Supply,
    BasicTable,
    SkusTable,
    FooterFields,
    OriginalReferenceDialog,
    SetReferenceCity,
    AssociatedGoodsModal,
    SeniorLinkedDialog,
    BtnRender
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      supplyInfo: {
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        supMainCategoryId: '', // 供应商主营品类id
        supMainCategoryName: '', // 供应商主营品类name
        supManagerHrAreaName: '', // 供应商管理区域
        freightPayer: '' // 运费承担方
      },
      supplyPriceType: '2', // 供货价格类型，1为统一进价，2为区域进价，默认为2
      commitState: '', // 单据状态
      taxRateInvoiceInfo: { // 发票类型，税率信息
        taxRate: '',
        invoiceType: '',
        invoiceTypeName: ''
      },
      viewReferenceCityTable: { // 参照城市查看页面表格
        columns: viewReferenceCityColumns, // 表格columns
        list: [] // 表格数据
      },
      btnLoading: { // 按钮loading
        submit: false, // 提交
        export: false // 导出
      },
      tableInfo: {
        loading: false, // 表格加载loading
        list: [], // 表格数据
        unifiedList: [], // 统一进价表格数据
        areaList: [], // 区域进价表格数据
        columns: [] // 表格columns
      },
      footerFields: {}, // 表尾字段
      originalReference: { // 查看原价格组
        visible: false, // 弹框开关
        columns: originalReferCityColumns, // 原价格组columns
        params: {} // 原参照关系请求接口所需入参
      },
      setReferenceCity: { // 设置参照城市
        visible: false, // 弹框开关
        list: [], // 表格数据
        columns: showReferenceCityColumns, // 展示参照城市弹框columns
      },
      defaultReferenceCity: {}, // 统一进价设置参照城市的默认参照城市对象
      goodsLinked: { // 关联商品
        columns: associatedGoodsColumns, // 关联商品弹框表格columns
        requestApi: {
          url: ['/sysback/supplyskurel/getSupplySkuRelListForModifyTemplateCity'], // 查询接口
          type: 'post'
        },
        requestParams: [
          // 查询接口所需入参
          ...requiredParamsOther.requestParams,
          { name: 'isPurchaseMultiUnit', value: '2' }
        ],
        distinctParams: requiredParamsOther.distinctParams, // 查询接口区别未关联和已关联的入参
      },
      seniorLinked: { // 高级关联
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }]
      },
      apiObj: {
        getSameProductSupplyAreas: { // 获取参照城市历史参照
          url: '/sysback/supplyarea/getSameProductSupplyAreas',
          type: 'post'
        },
        refreshSupplyAreaPrice: { // 提交已设置的参照城市获取表格数据
          url: '/sysback/supplyareaprice/refreshSupplyAreaPrice',
          type: 'post'
        },
        getSupplyAreaBySkuNo: { // 查看原参照关系
          url: '/sysback/supplyarea/getSupplyAreaBySkuNo',
          type: 'post'
        },
        getTableData: { // 获取表格数据 - 关联商品和高级关联
          url: '/sysback/supplyareaprice/getListBySkuNos',
          type: 'post'
        },
        getCommitRecordDetailByRecordNo: { // 根据单据号获取已有信息 - 查看和修改页
          url: '/sysback/supplyareaprice/getCommitRecordDetailByRecordNo',
          type: 'post'
        },
        dataSubmit: { // 提交
          url: '/sysback/supplyareaprice/batchUpdateProductSupplyPrice',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    this.setCanOpeState()
    this.loadInitDataInMounted();
  },
  destoryed () {
    this.CLEAR_GOODS();
    this.DESTORY_STATE();
  },
  computed: {
    ...mapState('commonComps/skuAssociatedModal', [
      'associatedRowList'
    ]),
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    // 没有设置参照城市
    hasNoReferCity () {
      return this.setReferenceCity.list.length === 0;
    }
  },
  methods: {
    ...mapMutations('commonComps/skuAssociatedModal', [
      'ASSOCIATED_GOODS', 'CANCEL_GOODS', 'CHANGE_MODAL_SWITCH', 'CLEAR_GOODS'
    ]),
    ...mapMutations('commonComps/setReferenceCity', [
      'SET_TABLE_DATA',
      'SET_HISTORY_CITY_DATA',
      'SET_REFERENCE_CITIES',
      'SET_PURCHASE_PRICETYPE',
      'DESTORY_STATE'
    ]),
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const size = 'large';

      const btnsBar = [
        {
          label: '高级关联',
          method: this.handleSeniorLinked,
          icon: 'el-icon-link',
          hasAuth: true
        },
        {
          label: '关联商品',
          method: this.handleGoodsLinked,
          hasAuth: true
        },
        {
          label: '模板导出',
          method: this.handleExportTemplate,
          loading: this.btnLoading.export,
          disabled: this.tableInfo.list.length === 0
        },
        {
          label: '模板导入',
          action: 'sysback/supplyareaprice/importTemplateForUpdateReferenceCity',
          methods: {
            handleUploadSuccess: this.handleUploadSuccess,
            handleBeforeUpload: this.handleBeforeUpload
          },
          isImport: true,
          loadingFn: state => { this.tableInfo.loading = state },
          data: this.getImportParams()
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          canOpeState: this.canOpeState
        }
      ].map(item => ({ ...item, size })).filter(item => item?.canOpeState != false);
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    // 有单据号
    hasRecordNo () {
      return this.$route.query.recordNo;
    },
    // 没有选择供应商
    hasNotChooseSupply () {
      return !this.supplyInfo.supplierCode;
    },
    // 统一进价提交时，没有设置默认参照城市
    hasNotSetDefaultCity () {
      return !this.defaultReferenceCity?.templateCityUuid;
    },
    // 是查看页面
    isViewPage () {
      return this.$route.name === 'chageFromManageTemplateCityView';
    },
    // 是审核中单据
    isCommitRecord() {
      return this.commitState == 'COMMIT';
    },
    // 是修改页面
    isEditPage () {
      return this.$route.name === 'chageFromManageTemplateCityEdit';
    },
    // 是统一进价
    isUnifiedPurchase () {
      return this.supplyPriceType === '1';
    },
    // 是区域进价
    isAreaPurchase () {
      return this.supplyPriceType === '2';
    },
    // 当前集合为空，默认是表格数据
    isEmptyForCurrentList (list = this.tableInfo.list) {
      return list.length === 0;
    },
    // 进价、成本价小于等于零
    isLessThanZeroForPrice (dataSource = this.tableInfo.list) {
      return dataSource.some(row => {
        const needJudgeFields = [
          row.mainPurchasePriceUpdate || 0, // 主计量进价
          row.mainUnitCostPriceUpdate || 0, // 主计量成本
        ];
        return needJudgeFields.some(item => item <= 0);
      });
    },
    // 切换供货价格类型
    handleChangeTypeBySupplyPrice () {
      this.setTableColumnsBySupplyPriceType(); // 设置当前进价类型对应的表格columns
      this.setTableDataBySupplyPriceType(); // 设置当前进价类型对应的表格数据
      this.resetReferenceCityData(); // 清空参照关系
    },
    // 设置参照城市关系
    handleSetRelationByReferCity () {
      if (this.hasNotChooseSupply()) {
        return this.$message.warning('请先选择供应商');
      }
      if (this.isEmptyForCurrentList()) {
        return this.$message.warning('请先关联商品');
      }
      const isConsistent = this.getConsistentForSaleAreas();
      if (!isConsistent) {
        return this.$message.warning('商品销售区域必须一致');
      }
      this.setReferenceCity.visible = true;
    },
    // 高级关联
    handleSeniorLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('高级关联'));
      this.seniorLinked.visible = true;
    },
    // 关联商品
    handleGoodsLinked () {
      if (this.hasNotChooseSupply()) {
        return this.$message.warning('请先选择供应商');
      }
      sessionStorage.setItem('buttonId', getBtnsId('关联商品'));
      this.CHANGE_MODAL_SWITCH(true);
      this.$nextTick(() => {
        this.$refs.goodsLinked.getDataListAction();
      });
    },
    // 模板导出
    handleExportTemplate () {
      if (this.hasNoReferCity) return this.$message.warning('请先设置参照城市');
      this.exportReferData();
    },
    // 模板导入前置钩子
    handleBeforeUpload () {
      if (this.hasNotChooseSupply()) {
        this.$message.warning('请先选择供应商');
        return false;
      }
      if (this.isEmptyForCurrentList()) {
        this.$message.warning('请先关联商品');
        return false;
      }
      if (this.hasNoReferCity) {
        this.$message.warning('请先设置参照城市');
        return false;
      }
    },
    // 模板导入
    handleUploadSuccess (res) {
      if (res?.retData) {
        this.tableInfo.list = res.retData.map(item => ({
          ...item,
          ...item.supplyInfoDTO,
          ...item.supplyProductInfo,
          supplyUuid: this.supplyInfo.supplierCode,
          purchasePriceTypeUpdate: this.supplyPriceType,
          taxRate: this.taxRateInvoiceInfo.taxRate,
          invoiceType: this.taxRateInvoiceInfo.invoiceType,
          invoiceTypeName: this.taxRateInvoiceInfo.invoiceTypeName,
        }));
        this.tableInfo.list.forEach(item => {
          this.handleRowChange(item)
        });
      }
    },
    // 获取导入模板入参
    getImportParams () {
      const {
        skuNos, supplyAreaParams, supplyUuid, supplyPriceType
      } = this.getParamsByReferenceCitySet();
      const uploadData = {
        supplyUuid,
        supplyPriceType,
        skuNos: skuNos.join(',')
      }
      const templateCityUuids = supplyAreaParams
        .filter(item => item.templateCityUuid)
        .map(item => item.templateCityUuid)
      const defaultTempCity = {
        defaultTemplateCityUuid: this.defaultReferenceCity?.templateCityUuid,
        defaultTemplateCityName: this.defaultReferenceCity?.templateCityName
      }
      if (this.isAreaPurchase()) { // 区域价格
        return {
          ...uploadData,
          templateCityUuids: templateCityUuids.join(',')
        }
      }
      // 统一价格
      return { ...uploadData, ...defaultTempCity };
    },
    // 导出参照数据
    async exportReferData () {
      const loadingFn = state => { this.btnLoading.export = state };
      const uuid = generateUuid();
      const data = {
        ...this.getParamsByReferenceCitySet(),
        productType: '1', // 1为单计量。2为多计量
        uuid,
        defaultTemplateCityUuid: this.defaultReferenceCity?.templateCityUuid,
        defaultTemplateCityName: this.defaultReferenceCity?.templateCityName
      }
      const res = await exportTemplateService(data, loadingFn);
      createExcelByExport({ res, excelTitle: `修改参照城市-单计量_${uuid}` });
    },
    // 删除对应行表格row
    handleDeleteTableRow (row, index) {
      // 取消关联商品的关联关系
      this.CANCEL_GOODS({ row });
      this.tableInfo.list = this.tableInfo.list.filter(item => row.skuNo !== item.skuNo);
    },
    // 提交
    handleSubmit () {
      if (this.tableInfo.list.length > EDIT_REFERENCE_CITY_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${EDIT_REFERENCE_CITY_AMOUNT}`);
      }
      if (this.isUnifiedPurchase() && this.hasNotSetDefaultCity()) { // 当前供货价格类型为统一进价，且没有设置默认参照城市
        return this.$message.warning('请设置默认参照城市');
      }
      if (this.isAreaPurchase() && this.isEmptyForCurrentList(this.setReferenceCity.list)) { // 当前供货价格类型为区域进价，且没有设置参照城市关系
        return this.$message.warning('请先设置参照城市');
      }
      if (this.isLessThanZeroForPrice()) {
        return this.$message.warning('进价、成本价不可以小于等于0');
      }
      this.submitPurchaseData();
    },
    // 查看原参照关系
    handleViewOriginalReference (row) {
      this.setParamsByViewOriginalReference(row);
      this.originalReference.visible = true;
    },
    // 表格数据更改需要相关字段进行计算
    handleRowChange (row) {
      handlePriceChangeForSingleModify(row)
    },
    // 加载数据在mounted时期
    loadInitDataInMounted () {
      this.setTableColumnsBySupplyPriceType();
      const { recordNo } = this.$route.query;
      if (recordNo) {
        this.getExistPageInfoByRecordNo(recordNo);
      }
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction(h, { row }) {
      // if (this.isViewPage()) { return <div></div> }
      if (!this.isViewPage()) {
        return <div class="table-action">
          {<el-button
            size="mini"
            type="text"
            onClick={() => this.handleDeleteTableRow(row)}>
            删除</el-button>}
          {<el-button
            size="mini"
            type="text"
            onClick={() => this.handleViewOriginalReference(row)}
          >原参照关系</el-button>}
        </div>
      } else if (this.isViewPage() && this.isCommitRecord()) {
        return <div class="table-action">
          {<el-button
            size="mini"
            type="text"
            onClick={() => this.handleViewOriginalReference(row)}
          >原参照关系</el-button>}
        </div>
      } else {
        return <div></div>
      }
    },
    // 重置参照城市数据
    resetReferenceCityData () {
      this.setReferenceCity.list = [];
      this.defaultReferenceCity = {};
      this.DESTORY_STATE();
    },
    // 初始化参照城市相关数据
    initRelativeDataByReferenceCity (retData) {
      if (!retData) { return false; }
      if (this.tableInfo.list.length > 0 && this.supplyPriceType == 2) {
        // 判断原进价类型是否相投
        const hasDiffType = this.tableInfo.list.some(item => item.purchasePriceType != this.tableInfo.list[0].purchasePriceType)
        if (!hasDiffType) {
          // 获取历史参照
          this.getReferenceCityHistoryList()
        }
      }
      // 由于接口替换，返回字段变更，为不影响原有功能，在此初始化一次城市信息数据
      const getReferCitiesInfo = cityInfo => {
        return {
          ..._.pick(cityInfo, ['cityCode', 'cityName']),
          areaCode: cityInfo?.areaCode, // 业务区域编码
          areaName: cityInfo?.areaName, // 业务区域名称
          saleCityNo: cityInfo?.cityCode, // 销售区域编码
          saleCityName: cityInfo?.cityName, // 销售区域名称
          saleProvinceNo: cityInfo?.provinceCode, // 销售省编码
          saleProvinceName: cityInfo?.provinceName, // 销售省名称
        }
      }
      const initRetData = retData.map(item => ({
        ...getReferCitiesInfo(item),
        isSupply: '',
        templateCityName: '',
        templateCityUuid: '',
        buyPriceRatio: 1,
        costPriceRatio: 1
      }))
      const setCityData = []; // 设置参照城市弹框表格列表数据
      const supplyReferenceCityList = []; // 设置参照城市弹框城市下拉集合
      initRetData.forEach((item) => {
        setCityData.push({
          ...item,
          supplyUuid: this.supplyInfo.supplierCode,
        });
        supplyReferenceCityList.push({
          value: item.saleCityNo,
          label: item.saleCityName
        });
      });
      this.SET_TABLE_DATA(setCityData);
      this.SET_REFERENCE_CITIES(supplyReferenceCityList);
      this.SET_PURCHASE_PRICETYPE(this.supplyPriceType);
    },
    // 提交进价数据
    submitPurchaseData () {
      const supplyAreaParams = this.setReferenceCity.list.map(item => {
        return {
          isSupply: item.isSupply,
          supplyUuid: item.supplyUuid,
          ...this.getCommonObjByReferenceCity(item)
        }
      });
      const commonParams = { // 通用入参
        isPurchaseMultiUnit: '2',
        supplyPriceType: this.supplyPriceType,
        supplyAreaParams: supplyAreaParams,
        supplyAreaPriceParams: this.getSupplyAreaPriceParams()
      }
      const unifiedParams = { // 是统一进价时的特殊入参
        defaultTemplateCityUuid: this.defaultReferenceCity?.templateCityUuid,
        defaultTemplateCityName: this.defaultReferenceCity?.templateCityName
      }
      const data = this.isUnifiedPurchase() ? { ...commonParams, ...unifiedParams } : commonParams;
      this.postRequestSubmit({
        ...this.apiObj.dataSubmit,
        data
      }).then(res => {
        // console.log('res' + res);
        if (isResponseSuccess(res)) {
          this.validateFailCallBack(res.retData)
        }
      });
      // .then(retStatus => {
      //   if (retStatus) {
      //     this.$message.success('表格信息提交成功');
      //     this.$router.push({ name: 'chageFromManageList' });
      //   }
      // });
    },
    // 校验异常信息回调
    validateFailCallBack(response) {
      const { hasErrorMsg, batchUpdateProductSupplyPriceErrorMsgVoList } = response
      // console.log('hasErrorMsg' + hasErrorMsg);
      // console.log('batchUpdateProductSupplyPriceErrorMsgVoList:' + batchUpdateProductSupplyPriceErrorMsgVoList);
      if (!hasErrorMsg) {
        // 没有异常信息
        this.$message.success('表格信息提交成功');
        this.$router.push({ name: 'chageFromManageList' });
      } else {
        // 存在异常信息
        if (!this.tableInfo.columns.some(item => item.key == 'errorMsg')) {
          this.tableInfo.columns.unshift(ERRORS_COLUMN);
        }
        // console.log('tableInfo.list:' + this.tableInfo.list);
        // 展示对应的异常信息
        this.tableInfo.list.forEach(item => {
          const spliceKey = this.isUnifiedPurchase() ? `${item.supplyUuid}_${item.skuNo}` : `${item.supplyUuid}_${item.skuNo}_${item.templateCityUuid}`;
          // console.log('spliceKey:' + spliceKey);
          batchUpdateProductSupplyPriceErrorMsgVoList.forEach(ele => {
            if (spliceKey == ele.key) {
              item.errorMsg = ele.value
            }
          })
        });
        return this.$alert('存在禁止提交原因，无法提交单据，请在详情页中查看具体原因', '提交错误提示', {
          confirmButtonText: '确定',
          type: 'warning',
        });
      }
    },
    // 获取页面标题
    getPageTitle () {
      const title = '修改参照城市';
      if (this.isViewPage()) {
        return `${title}-表单查看页面`;
      }
      if (this.isEditPage()) {
        return `${title}-表单修改页面`;
      }
      return title;
    },
    // 获取选择的供应商信息
    getSupplierInfoByChoosed (data) {
      if (this.supplyInfo.supplierCode !== data.supplierCode) { // 更换供应商时，要清空参照和表格数据
        this.setCacheTableData();
        this.setTableDataBySupplyPriceType();
        this.resetReferenceCityData();
      }
      this.setRelativeInfoBySupplier(data);
      this.setRelativeInfoByTaxRate(data);
    },
    // 获取供货价格方式文本 （查看页面）
    getSupplyPriceTypeStr () {
      return getEchoTextByValue({
        val: this.supplyPriceType,
        firstText: '统一进价',
        secondText: '区域进价'
      });
    },
    // 获取参照城市列表
    async getReferenceCityList () {
      const data = { areaCode: this.tableInfo.list[0]?.supplyProductInfo?.saleAreaCodes }
      const res = await getSupplyCityByAreaCodesService(data)
      if (!res?.retData) return false
      this.initRelativeDataByReferenceCity(res.retData)
      return true
    },
    // 获取历史参照城市列表
    async getReferenceCityHistoryList () {
      const retData = await this.postRequestOtherAction({
        ...this.apiObj.getSameProductSupplyAreas,
        data: {
          supplyUuid: this.supplyInfo.supplierCode,
          skuNos: this.tableInfo.list.map(item => item.skuNo)
        },
        isFormData: false
      })
      if (retData) {
        this.SET_HISTORY_CITY_DATA(retData)
      }
    },
    // 获取设置完成后的参照城市数据
    getReferenceCitiesBySet ({ tableData, defaultCity }) {
      this.setReferenceCity.list = tableData;
      this.defaultReferenceCity = defaultCity;
      if (this.isAreaPurchase()) {
        this.getTableDataByReferenceCitySet();
      }
    },
    // 获取初始统一进价表格数据
    getInitTableDataByUnifiedPurchase (dataSource) {
      return _.cloneDeep(dataSource).reduce((value, item) => {
        if (value.findIndex(row => row.skuNo === item.skuNo) === -1) {
          value.push(item);
        }
        return value;
      }, [dataSource[0]]);
    },
    // 获取初始化初始表格数据的现值
    getInitUpdateValByRetData (retData) {
      const {
        taxRate,
        invoiceType,
        invoiceTypeName
      } = this.taxRateInvoiceInfo;
      return _.cloneDeep(retData).map(item => {
        item.productName = item.supplyProductInfo?.productName || '';
        item.specDetailStr = item.supplyProductInfo?.specDetailStr || '';
        item.saleAreaShortNames = item.supplyProductInfo?.saleAreaShortNames || '';
        item.purchasePriceNoteUpdate = '';
        item.purchasePriceTypeUpdate = this.supplyPriceType;
        item.mainPurchasePriceUpdate = item.mainPurchasePrice;
        item.factoryFacePriceUpdate = item.factoryFacePrice;
        item.purchasePriceNoteUpdate = item.purchasePriceNote;
        item.freightRatioUpdate = item.freightRatio;
        item.packRatioUpdate = item.packRatio;
        item.processChargesRatioUpdate = item.processChargesRatio;
        item.rebateRatioUpdate = item.rebateRatio;
        item.rebateRatioDescUpdate = item.rebateRatioDesc;
        item.mainUnitCostPriceUpdate = item.mainUnitCostPrice;
        item.taxRate = taxRate;
        item.invoiceType = invoiceType;
        item.invoiceTypeName = invoiceTypeName;
        this.handleRowChange(item)
        return item;
      });
    },
    // 获取设置完参照城市提交接口的入参
    getParamsByReferenceCitySet () {
      const referSelfCityList = this.setReferenceCity.list.filter(item => item.saleCityNo === item.templateCityUuid);
      const supplyAreaParams = referSelfCityList.map(item => this.getCommonObjByReferenceCity(item));
      const skuNos = _.uniq(this.tableInfo.list.map(item => item.skuNo));
      return {
        skuNos,
        supplyAreaParams,
        supplyPriceType: this.supplyPriceType,
        supplyUuid: this.supplyInfo.supplierCode
      }
    },
    // 获取表格数据 by 设置完参照城市(只有是区域进价的时候才会调用)
    getTableDataByReferenceCitySet () {
      this.postRequestTableData({
        ...this.apiObj.refreshSupplyAreaPrice,
        data: this.getParamsByReferenceCitySet()
      }).then(retData => {
        if (retData) {
          this.tableInfo.list = this.getInitUpdateValByRetData(retData);
        } else {
          this.resetReferenceCityData(); // 如果获取数据失败，参照关系清空
        }
      });
    },
    // 获取表格数据 by 高级关联
    getTableDataBySeniorLinked (skuNos) {
      this.CLEAR_GOODS(); // 清空关联商品
      this.postRequestTableData({
        ...this.apiObj.getTableData,
        data: {
          skuNos,
          supplyCodes: [this.supplyInfo.supplierCode],
          purchaseMultiUnitFlag: '2' // 单计量 2， 多计量 1
        }
      }).then(retData => {
        if (retData) {
          this.resetReferenceCityData();
          this.setCacheTableData(retData);
          this.setTableDataBySupplyPriceType();
        }
      });
    },
    // 获取表格数据 by 关联商品
    getTableDataByGoodsLinked () {
      const skuNos = getListByMapDimensionKey(this.associatedRowList, 'skuNo');
      if (this.isEmptyForCurrentList(skuNos)) {
        this.tableInfo.list = [];
        this.setCacheTableData();
        return false;
      }
      this.postRequestTableData({
        ...this.apiObj.getTableData,
        data: {
          skuNos,
          supplyCodes: [this.supplyInfo.supplierCode]
        }
      }).then(retData => {
        if (retData) {
          this.resetReferenceCityData();
          this.setCacheTableData(retData);
          this.setTableDataBySupplyPriceType();
        }
      });
    },
    // 获取已有页面信息 by 单据号 recordNo
    getExistPageInfoByRecordNo (recordNo) {
      const { url, type } = this.apiObj.getCommitRecordDetailByRecordNo;
      this.postRequestTableData({
        url: `${url}?recordNo=${recordNo}`,
        type
      }).then(retData => {
        if (!retData) { return false; }
        const { supplyAreaVos, supplyAreaPriceParamVos } = retData;
        this.setRelativeInfoBySupplier(retData);
        this.footerFields = retData;
        this.viewReferenceCityTable.list = supplyAreaVos; // 参考城市关系表格数据
        this.supplyPriceType = supplyAreaPriceParamVos[0].purchasePriceType; // 供货价格类型
        this.tableInfo.list = supplyAreaPriceParamVos;
        const { commitState } = retData;
        this.commitState = commitState;
        // console.log("commitState:" + this.commitState);
        // console.log("isViewPage:" + this.isViewPage());
        // console.log("isCommitRecord:" + this.isCommitRecord());
      });
    },
    // 获取表格数据商品销售区域的一致性
    getConsistentForSaleAreas () {
      let isConsistentForSaleAreas = true;
      let unduplicatedSaleAreaCodes = new Set();
      // 点击设置时判断 必须关联商品且关联的商品销售区域必须一致，否则不能进行设置。
      this.tableInfo.list.forEach((item) => {
        unduplicatedSaleAreaCodes.add(item.supplyProductInfo.saleAreaCodes);
      });
      if (unduplicatedSaleAreaCodes.size > 1) {
        isConsistentForSaleAreas = false;
      }
      return isConsistentForSaleAreas;
    },
    // 设置原参照关系请求入参
    setParamsByViewOriginalReference (row) {
      this.originalReference.params = {
        params: {
          supplyUuid: this.supplyInfo.supplierCode,
          skuNo: row.skuNo
        },
        ...this.apiObj.getSupplyAreaBySkuNo
      };
    },
    // 设置表格columns by 供货价格类型
    setTableColumnsBySupplyPriceType () {
      if (this.isUnifiedPurchase()) { // 统一进价
        this.tableInfo.columns = this.isViewPage() ? _.cloneDeep(viewUnifiedPurchaseColumns) : _.cloneDeep(unifiedPurchaseColumns);
      }
      if (this.isAreaPurchase()) { // 区域进价
        this.tableInfo.columns = this.isViewPage() ? _.cloneDeep(viewAreaPurchaseColumns) : _.cloneDeep(areaPurchaseColumns);
      }
    },
    // 设置供应商相关信息
    setRelativeInfoBySupplier (data) {
      const { supplierCode, supplierName, supMainCategoryId, supMainCategoryName, supManagerHrAreaName, freightPayer } = data;
      this.supplyInfo = {
        supplierCode,
        supplierName,
        supMainCategoryId,
        supMainCategoryName,
        supManagerHrAreaName,
        freightPayer
      };
    },
    // 设置税率相关信息
    setRelativeInfoByTaxRate (data) {
      const { taxRate, invoiceType, invoiceTypeName } = data;
      this.taxRateInvoiceInfo = {
        taxRate,
        invoiceType,
        invoiceTypeName
      }
    },
    // 缓存初始表格数据
    setCacheTableData (retData) {
      if (!retData) {
        this.tableInfo.unifiedList = [];
        this.tableInfo.areaList = [];
        return false;
      }
      const updateTableData = this.getInitUpdateValByRetData(retData);
      this.tableInfo.unifiedList = this.getInitTableDataByUnifiedPurchase(updateTableData);
      this.tableInfo.areaList = updateTableData;
    },
    // 根据进价类型设置对应表格数据
    setTableDataBySupplyPriceType () {
      if (this.isUnifiedPurchase()) { // 是统一进价
        this.tableInfo.list = _.cloneDeep(this.tableInfo.unifiedList);
      }
      if (this.isAreaPurchase()) { // 是区域进价
        this.tableInfo.list = _.cloneDeep(this.tableInfo.areaList);
      }
      this.tableInfo.list.forEach(item => { item.purchasePriceTypeUpdate = this.supplyPriceType });
    },
    // 获取表格数据post请求
    async postRequestTableData ({ url, type, data = {}, isFormData = false }) {
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 提交post请求
    async postRequestSubmit ({ url, type, data = {}, isFormData = false }) {
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.btnLoading.submit = false;
        if (isResponseSuccessState(res.retStatus)) {
          return res;
        }
      } catch (err) {
        this.btnLoading.submit = false;
      }
    },
    // 其他操作post请求
    async postRequestOtherAction ({ url, type, data = {}, isFormData = false }) {
      const res = await ApiRequest(url, type, data, isFormData);
      if (isResponseSuccess(res)) {
        return res.retData;
      }
    },
    // 获取公共参数对象 by 设置参照城市后获取表格数据接口入参 和 提交接口的入参需使用
    getCommonObjByReferenceCity (item) {
      return {
        saleAreaName: item.saleAreaName,
        saleAreaUuid: item.saleAreaUuid,
        saleCityName: item.saleCityName,
        saleCityUuid: item.saleCityNo,
        saleProvinceUuid: item.saleProvinceNo,
        saleProvinceName: item.saleProvinceName,
        templateCityName: item.templateCityName,
        templateCityUuid: item.templateCityUuid,
        buyPriceRatio: item.buyPriceRatio,
        costPriceRatio: item.costPriceRatio
      }
    },
    // 获取并重组提交接口所需入参 supplyAreaPriceParams
    getSupplyAreaPriceParams () {
      return this.tableInfo.list.map(item => {
        return {
          costPriceLimitTop: item.costPriceLimitTop,
          costPriceLimitBottom: item.costPriceLimitBottom,
          freightPayer: this.supplyInfo?.freightPayer,
          supMainCategoryId: this.supplyInfo?.supMainCategoryName,
          abnormalPurchaseConvertRatio: item.abnormalPurchaseConvertRatioUpdata,
          actualConvertRatio: item.actualConvertRatioUpdate,
          actualConvertRatioCostPrice: item.actualConvertRatioCostPriceUpdate,
          addPriceType: item.addPriceType,
          addPriceTypeStr: item.addPriceTypeStr,
          changePriceReason: item.changePriceReason,
          factoryCode: item.factoryCode,
          factoryFacePrice: item.factoryFacePriceUpdate,
          freightRatio: item.freightRatioUpdate,
          mainPurchasePrice: item.mainPurchasePriceUpdate,
          mainPurchasePriceFloatRadio: item.mainPurchasePriceFloatRadio,
          mainUnitCostPrice: item.mainUnitCostPriceUpdate,
          oldAbnormalPurchaseConvertRatio: item.abnormalPurchaseConvertRatio,
          oldActualConvertRatioCostPrice: item.actualConvertRatioCostPrice,
          oldFactoryFacePrice: item.factoryFacePrice,
          oldFreightRatio: item.freightRatio,
          oldMainPurchasePrice: item.mainPurchasePrice,
          mainUnitCostFloatPrice: item.mainUnitCostFloatPrice,
          oldMainUnitCostPrice: item.mainUnitCostPrice,
          oldPackRatio: item.packRatio,
          oldProcessChargesRatio: item.processChargesRatio,
          oldPurchasePrice: item.purchasePrice,
          oldPurchasePriceNote: item.purchasePriceNote,
          oldPurchasePriceType: item.purchasePriceType,
          oldRebateRatio: item.rebateRatio,
          oldRebateRatioDesc: item.rebateRatioDesc,
          oldTheoryConvertRatioCostPrice: item.theoryConvertRatioCostPrice,
          packRatio: item.packRatioUpdate,
          processChargesRatio: item.processChargesRatioUpdate,
          productName: item.supplyProductInfo?.productName || '',
          productUuid: item.supplyProductInfo?.productUuid || '',
          purchasePrice: item.purchasePriceUpdate,
          purchasePriceNote: item.purchasePriceNoteUpdate,
          purchasePriceType: this.supplyPriceType,
          purchasePriceTypeStr: item.purchasePriceTypeStrUpdate,
          rebateRatio: item.rebateRatioUpdate,
          rebateRatioDesc: item.rebateRatioDescUpdate,
          supplyUuid: item.supplyUuid ?? this.supplyInfo.supplierCode,
          saleAreaShortNames: item.supplyProductInfo?.saleAreaShortNames || '',
          skuNo: item.skuNo,
          spuNo: item.spuNo,
          specDetailStr: item.supplyProductInfo?.specDetailStr || '',
          supplyGoodsUnit: item.supplyProductInfo?.supplyGoodsUnit || '',
          supplyManagerArea: item.supplyInfoDTO?.supplyManagerArea || '',
          supplyName: item.supplyInfoDTO?.supplyName || '',
          templateCityName: item.templateCityName,
          templateCitySaleAreaName: item.templateCitySaleAreaName,
          templateCitySaleAreaNo: item.templateCitySaleAreaNo,
          templateCityUuid: item.templateCityUuid,
          theoryConvertRatio: item.theoryConvertRatio,
          theoryConvertRatioCostPrice: item.theoryConvertRatioCostPrice,
          unitName: item.supplyProductInfounitName
        }
      });
    }
  }
}
</script>
<style lang="less" scoped>
.margin--to--bottom {
  margin-bottom: 10px;
}
.supplier--info--wrap {
  min-width: 180px;
  margin-left: 10px;
  &:first-child {
    margin-left: 0px;
  }
}
/deep/ .el-table__body-wrapper{
  z-index: 2
}
</style>
